<template>
    <main class="main" id="top" style="overflow: hidden;margin-bottom: 100px;margin-top: 40px;">
        <floatBall />

        <el-overlay :mask="loginDialogVisible" @click="() => {
            loginDialogVisible = false;
        }" style="display: flex;justify-content: center;align-items: center;transition: all 0.6s">

            <div v-if="loginDialogVisible"
                style="position: relative;width:768px;height: 480px;overflow: hidden;border-radius: 10px;">
                <Login @afterLogin="() => {
                    loginDialogVisible = false;
                    checkLogin()
                }" />
            </div>

        </el-overlay>
        <el-dialog v-model='userInfoVisible' style="border-radius: 10px;">
            <template #title>
                <span style="font-weight: bold;">请完善基础信息</span>
            </template>
            <userInfoForm @closeUserInfoView="() => {
                userInfoVisible = false;
                checkLogin()
            }" style="padding: 20px;" />

        </el-dialog>
        <DeviceDialogForm v-model:visible='deviceDialogFormVisible' :formType="currentFormType"
            :initialData="currentInstrument" @submit="handleFormSubmit" />

        <div class="container" id="formContainer"
            style="display: flex;flex-direction: column;background-color: #ffffff;margin-top: 30px;padding: 65px 60px;border-radius: 10px;max-width: 85%;">
            <div style="display: grid; grid-template-columns: 1fr auto; align-items: center; overflow: hidden;">
                <h3 style="color: var(--el-text-color-regular);font-weight: bold;float: left;">
                    客户项目需求表</h3>
                <div>
                    <el-text size="small">
                        表单编号：{{ formData.uuid }}</el-text>
                </div>
            </div>
            <div v-if="!isLoginAndInfo">
                <el-text type="danger" size="small">
                    <el-icon>
                        <WarningFilled />
                    </el-icon>
                    &ensp;您需要先登录并完成身份信息填写才可填表，
                    <el-text id="info_btn" type="primary" size="small" style="cursor: pointer;"
                        @click="checkLogin()">立即完成</el-text>
                </el-text>
            </div>


            <el-form name="form" size="large" :model="formData" ref="formRef" :rules="rules" label-width="250px"
                label-position="left" style="background-color: #ffffff;max-width: auto;margin-top: 50px;">

                <el-form-item label="应用场景：" prop="usageScene">
                    <el-select v-model="formData.usageScene" placeholder="选择您所应用的场景" size="default"
                        style="width: 240px">
                        <el-option v-for="item in UsageOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-input v-model="formData.usageDesc" style="width: 600px" :autosize="{ minRows: 2 }"
                        type="textarea" placeholder="请简要描述您项目的主要功能、应用场景、所属细分行业等" />
                </el-form-item>

                <el-form-item label="系统整体框图" prop="systemDiagram">
                    <template #label>
                        <el-tooltip content="请提供可视化的系统架构图，有助于我们理解系统的各个组成部分及其相互关系，便于系统设计和实施" placement="top">
                            <div class="d-flex flex-align-center ">
                                <span class="el-form-item__label">系统整体框图</span>
                                <el-icon>
                                    <QuestionFilled />
                                </el-icon>
                            </div>
                        </el-tooltip>
                    </template>
                    <el-upload ref="sysUpload" class="upload-demo" action="" list-type="picture-card" :limit="5"
                        :on-exceed="handleExceed" :on-change="handleChange" v-model:file-list="imgList"
                        :on-remove="handleRemove" :on-preview="handlePreview" :on-success="handleUploadSuccess"
                        :on-error="handleUploadError" accept=".jpg,.jpeg,.png,.pdf" :auto-upload="false"
                        :multiple="true">

                        <el-icon class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #file="{ file }">
                            <div>
                                <div v-if="file.name.endsWith('.pdf')">
                                    <vue-pdf-embed :page="0" :source="file.url" />
                                </div>

                                <img v-else class="el-upload-list__item-thumbnail" style="object-fit: cover"
                                    :src="file.url" alt="" />

                                <span class="el-upload-list__item-actions">
                                    <span class="el-upload-list__item-preview" @click="handlePreview(file)">
                                        <el-icon><zoom-in /></el-icon>
                                    </span>
                                    <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                                        <el-icon>
                                            <Delete />
                                        </el-icon>
                                    </span>
                                </span>
                            </div>
                        </template>
                        <template v-slot:tip>
                            <div class="el-upload__tip">最多上传 5 张图片，图片大小不超过 20MB，文件类型仅支持 JPG / PNG / PDF</div>
                        </template>
                    </el-upload>
                    <el-dialog v-model="dialogVisibleimg" append-to-body width="70%">

                        <div v-if="dialogFileType === 'pdf'" id="vue-pdf-view">
                            <div id="page-view">
                                <vue-pdf-embed :source="dialogFileUrl" />
                            </div>
                        </div>

                        <img v-else width="100%" :src="dialogFileUrl" alt="" />

                    </el-dialog>
                </el-form-item>

                <el-form-item label="测量仪表" prop="measurementInstruments">
                    <div style="width: 100%;">
                        <el-button size="default" type="primary" @click="openDialog('measurement')">添加<el-icon
                                class="el-icon--right">
                                <Plus />
                            </el-icon></el-button>
                    </div>
                    <el-table :data="formData.measurementInstruments" style="width: 600px" stripe>
                        <el-table-column prop="deviceName" align="center" label="设备名称">
                            <template #default="scope">
                                <el-tooltip v-if="scope.row.isUnknown" content="该设备未确定" placement="top">
                                    <span>
                                        <el-tag type="warning">
                                            <div class="d-flex flex-align-center">{{ scope.row.deviceName || "未确定"
                                                }}<el-icon>
                                                    <QuestionFilled />
                                                </el-icon></div>
                                        </el-tag>
                                    </span>
                                </el-tooltip>
                                <span v-else>{{ scope.row.deviceName }}</span>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="measurementParameter" label="测量参数"></el-table-column>
                        <el-table-column prop="measurementAccuracy" label="测量精度"></el-table-column>
                        <el-table-column prop="updateFrequency" label="数据更新频率"></el-table-column>
                        <el-table-column prop="otherRequirements" label="其他要求" width="180"></el-table-column> -->
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button size="mini"
                                    @click="editInstrument('measurement', scope.$index, scope.isUnknown)">编辑</el-button>
                                <el-button size="mini" type="danger"
                                    @click="deleteInstrument('measurement', scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>

                <el-form-item label="控制仪表" prop="controlInstruments">
                    <div style="width: 100%;">
                        <el-button size="default" type="primary" @click="openDialog('control')">添加<el-icon
                                class="el-icon--right">
                                <Plus />
                            </el-icon></el-button>
                    </div>
                    <el-table :data="formData.controlInstruments" style="width: 600px" stripe>
                        <el-table-column align="center" prop="deviceName" label="设备名称">
                            <template #default="scope">
                                <el-tooltip v-if="scope.row.isUnknown" content="该设备未确定" placement="top">
                                    <span>
                                        <el-tag type="warning">
                                            <div class="d-flex flex-align-center">{{ scope.row.deviceName || "未确定"
                                                }}<el-icon>
                                                    <QuestionFilled />
                                                </el-icon></div>
                                        </el-tag>
                                    </span>
                                </el-tooltip>
                                <span v-else>{{ scope.row.deviceName }}</span>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="controlObject" label="控制对象"></el-table-column>
                        <el-table-column prop="controlAccuracy" label="控制精度"></el-table-column>
                        <el-table-column prop="otherRequirements" label="其他要求" width="180"></el-table-column> -->
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button size="mini"
                                    @click="editInstrument('control', scope.$index, scope.isUnknown)">编辑</el-button>
                                <el-button size="mini" type="danger"
                                    @click="deleteInstrument('control', scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>

                <el-form-item style="font-weight: bold;margin-top: 30px;">
                    <template #label>
                        <el-tooltip content="如果您不确定该选择何种仪表来满足应用需求，请在此添加需求描述，我们将为您提供专业的选型服务" placement="top">
                            <div class="d-flex flex-align-center ">
                                <span class="el-form-item__label">需要协助选型的仪表</span>
                                <el-icon>
                                    <QuestionFilled />
                                </el-icon>
                            </div>
                        </el-tooltip>
                    </template>
                    <el-button size="default" type="warning" plain @click="openDialog('unknown')">添加<el-icon
                            class="el-icon--right">
                            <Plus />
                        </el-icon></el-button>
                </el-form-item>

                <el-form-item>
                    <template #label>
                        <el-tooltip placement="top">
                            <template #content>
                                <div>
                                    测控系统集成：提供电源系统、检测仪表与控制仪表的全面接入与整合，同时进行规范的系统测试，确保测控系统的无缝运作。<br>
                                    现场设备调试：我们的专业团队将亲临现场，进行设备的接入、开发调试和功能测试，确保一切运行顺畅。<br>
                                    教育培训：我们提供现场培训服务，帮助您的团队快速掌握设备操作与系统管理，确保最大化利用系统功能。<br>
                                </div>
                            </template>

                            <div class="d-flex flex-align-center ">
                                <span class="el-form-item__label">实施与支持服务(付费选项)</span>
                                <el-icon>
                                    <QuestionFilled />
                                </el-icon>
                            </div>
                        </el-tooltip>
                    </template>
                    <div class="d-flex align align-items-start">
                        <div>
                            <el-checkbox v-model="formData.tecService.sysIntegration" label="测控系统集成" size="large" />
                            <el-checkbox v-model="formData.tecService.onSiteDebugging" label="现场设备调试" size="large" />
                            <el-checkbox v-model="formData.tecService.educationTraining" label="教育培训" size="large" />
                        </div>


                    </div>
                </el-form-item>

                <el-form-item style="font-weight: bold;margin-top: 30px;" label="">
                    <template #label>
                        <el-tooltip content="提供售前与售后全流程支持服务" placement="top">
                            <div class="d-flex flex-align-center ">
                                <span class="el-form-item__label">服务顾问编码</span>
                                <el-icon>
                                    <QuestionFilled />
                                </el-icon>
                            </div>
                        </el-tooltip>
                    </template>
                    <el-input v-model="formData.consultantCode" style="width: 240px" placeholder="请输入顾问代码" />
                </el-form-item>




            </el-form>
            <el-button type="primary" size="large" style="width: 400px;margin-top: 50px;align-self: center"
                @click="handleSubmit">{{ route.query.uuid ? '修改' : '提交'
                }}</el-button>
        </div>





        <!-- <el-form :model="form" label-width="auto" style="max-width: 600px">
                <el-form-item label="Activity name">
                    <el-input v-model="form.name" />
                </el-form-item>

            </el-form> -->



    </main>

</template>

<script setup>
import { onMounted, ref, getCurrentInstance, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import DeviceDialogForm from './components/deviceDialogForm.vue';
import { userInfo, checkTokenAndFetchUserInfo, validateUserInfo } from '@/utils/auth';
import Login from '@/components/login/loginBox.vue'
import floatBall from '@/components/floatBall/floatBall.vue'

import userInfoForm from '@/components/userInfoForm/userInfoForm.vue'
import VuePdfEmbed from "vue-pdf-embed";
import { v4 as uuidv4 } from 'uuid';
import { useRoute, useRouter } from 'vue-router';


const router = useRouter();
const route = useRoute();

const { proxy } = getCurrentInstance(); // 获取当前实例以访问全局属性

const currentFormType = ref('');
const deviceDialogFormVisible = ref(false);
const currentInstrument = ref(null);
const currentInstrumentIndex = ref(-1);

const loginDialogVisible = ref(false);
const userInfoVisible = ref(false);
const isLoginAndInfo = ref(false);

const sysUpload = ref();
const imgList = ref([]);
const dialogVisibleimg = ref(false);
const dialogFileUrl = ref('');
const dialogFileType = ref('');

const formRef = ref()


const UsageOptions = [
    {
        value: '科研机构',
        label: '科研机构',
    },
    {
        value: '工业场所',
        label: '工业场所',
    },
    {
        value: '基础教学',
        label: '基础教学',
    },
    {
        value: '其他',
        label: '其他',
    },
]

const formData = ref({
    uuid: uuidv4(),
    userId: '',                  // 用户 ID
    usageScene: '',              // 应用场景
    usageDesc: '',               // 应用描述
    systemDiagram: [],           // 系统整体框图（上传的图片 URL）
    measurementInstruments: [],  // 测量仪表数组
    controlInstruments: [],      // 控制仪表数组
    tecService: [{
        sysIntegration: false,    // 测控系统集成
        onSiteDebugging: false,   // 现场设备调试
        educationTraining: false, // 教育培训
    }],              // 技术服务
    consultantCode: '',          // 服务顾问编码
    state: 0,                    // 状态
    activeMessage: [],           // 活动消息
});

const checkUsageScene = (rule, value, callback) => {
    if (!formData.value.usageScene) {
        callback(new Error('请选择应用场景'));
    } else {
        callback();
    }
}

const checkSystemDiagram = (rule, value, callback) => {
    if (imgList.value.length === 0) {
        callback(new Error('请上传系统框图'));
    } else {
        callback();
    }
}
const checkMeasurementInstruments = (rule, value, callback) => {
    if (formData.value.measurementInstruments.length === 0) {
        callback(new Error('请添加测量仪表'));
    } else {
        callback();
    }
}

const checkControlInstruments = (rule, value, callback) => {
    if (formData.value.controlInstruments.length === 0) {
        callback(new Error('请添加控制仪表'));
    } else {
        callback();
    }
}


const rules = ref({
    usageScene: [
        { validator: checkUsageScene, trigger: 'blur' }
    ],
    systemDiagram: [
        { validator: checkSystemDiagram, trigger: 'blur' }
    ],
    measurementInstruments: [
        { validator: checkMeasurementInstruments, trigger: 'blur' }
    ],
    controlInstruments: [
        { validator: checkControlInstruments, trigger: 'blur' }
    ],
});



const openDialog = (type, instrument = null, index = -1) => {
    currentFormType.value = type;
    currentInstrument.value = instrument
        ? { ...instrument }
        : { InstrumentType: type === 'unknown' ? '' : type, isUnknown: type === 'unknown' };
    console.log('currentInstrument', currentInstrument);
    currentInstrumentIndex.value = index;
    deviceDialogFormVisible.value = true;
};

const handleFormSubmit = (deviceData) => {
    if (deviceData.InstrumentType === 'measurement') {
        if (currentInstrumentIndex.value !== -1) {
            formData.value.measurementInstruments.splice(currentInstrumentIndex.value, 1, deviceData);
        } else {
            formData.value.measurementInstruments.push(deviceData);
        }
    } else if (deviceData.InstrumentType === 'control') {
        if (currentInstrumentIndex.value !== -1) {
            formData.value.controlInstruments.splice(currentInstrumentIndex.value, 1, deviceData);
        } else {
            formData.value.controlInstruments.push(deviceData);
        }
    }
    deviceDialogFormVisible.value = false;
    currentInstrument.value = null;
    currentInstrumentIndex.value = -1;
};

const editInstrument = (type, index, isUnknown) => {
    let instrument;


    if (type === 'measurement') {
        instrument = formData.value.measurementInstruments[index];
        if (isUnknown) {
            openDialog("unknown", instrument, index);
            return
        }
        openDialog(type, instrument, index);

    } else if (type === 'control') {
        instrument = formData.value.controlInstruments[index];
        if (isUnknown) {
            openDialog("unknown", instrument, index);
            return
        }
        openDialog(type, instrument, index);

    }
};

const deleteInstrument = (type, index) => {

    ElMessageBox.confirm(
        `是否确定删除该仪表`,
        '删除提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        if (type === 'measurement') {
            formData.value.measurementInstruments.splice(index, 1);
        } else if (type === 'control') {
            formData.value.controlInstruments.splice(index, 1);
        }
    }).catch(() => {
    });


};



onMounted(async () => {
    document.body.style.backgroundColor = '#f6f6f6';
    checkLogin()    // 检查用户登录状态

    if (route.query.uuid) {
        const res = await proxy.$axios.get('/app/demand/info/getDemandById', {
            params: {
                uuid: route.query.uuid
            }
        })
        if (res.data.code === 1000) {
            formData.value = res.data.data
            downloadFile()
            // await saveToLocalStorage()
            // getDataFromLocalStorage()


        } else {
            ElMessage.error('获取表单失败')
            throw new Error(res.data.message)
        }
    } else {
        // getDataFromLocalStorage()
    }

});
// import throttle from 'lodash/throttle';

// const clearFormStorage = () => {
//     localStorage.removeItem('formData');
//     localStorage.removeItem('imgList');
// };


// const getDataFromLocalStorage = () => {
//     const savedFormData = localStorage.getItem('formData');
//     const savedImgList = localStorage.getItem('imgList');

//     if (savedFormData) {
//         formData.value = JSON.parse(savedFormData);
//     }

//     if (savedImgList) {
//         imgList.value = JSON.parse(savedImgList);
//     }
// };

// const saveToLocalStorage = throttle(() => {
//     localStorage.setItem('formData', JSON.stringify(formData.value));
//     localStorage.setItem('imgList', JSON.stringify(imgList.value));
// }, 1000); // 每 1 秒最多保存一次

// watch([formData, imgList], saveToLocalStorage, { deep: true });


const fileFromURL = async (url) => {
    const response = await fetch(url);
    const blob = await response.blob();
    const filename = url.substring(url.lastIndexOf('/') + 1);
    const res = {
        url: url,
        name: filename,
        status: 'ready',
        uid: Math.random().toString(36).substring(2),
        raw: new File([blob], filename, { type: blob.type })
    }
    return res

};

const downloadFile = async () => {
    for (let i = 0; i < formData.value.systemDiagram.length; i++) {
        imgList.value[i] = await fileFromURL(formData.value.systemDiagram[i])
    }
    formData.value.systemDiagram = []
    console.log("measurementInstruments", formData.value.measurementInstruments);
    for (const item of formData.value.measurementInstruments) {
        for (let i = 0; i < item.fileList.manual.length; i++) {
            item.fileList.manual[i] = await fileFromURL(item.fileList.manual[i])
        }

        for (let i = 0; i < item.fileList.photos.length; i++) {
            item.fileList.photos[i] = await fileFromURL(item.fileList.photos[i])
        }

    }
    for (const item of formData.value.controlInstruments) {
        for (let i = 0; i < item.fileList.manual.length; i++) {
            item.fileList.manual[i] = await fileFromURL(item.fileList.manual[i])
        }

        for (let i = 0; i < item.fileList.photos.length; i++) {
            item.fileList.photos[i] = await fileFromURL(item.fileList.photos[i])
        }
    }
}

watch(loginDialogVisible, (newVal) => {
    if (newVal) {
        document.body.style.overflow = 'hidden'
    } else {
        document.body.style.overflow = '';
    }
});

watch(userInfoVisible, (newVal) => {
    if (newVal) {
        document.body.style.overflow = 'hidden'
    } else {
        document.body.style.overflow = '';
    }
});

const checkLogin = async () => {
    // 这里应该检查用户的登录状态，例如从 Vuex 或 localStorage 中获取

    await checkTokenAndFetchUserInfo();

    if (!userInfo.value) {
        ElMessage.error('您还未登录，请先登录');
        loginDialogVisible.value = true;
        return false
    } else if (!validateUserInfo()) {
        userInfoVisible.value = true;
        return false
    }
    isLoginAndInfo.value = true;
    return true
};


const handleExceed = (file, fileList) => {
    imgList.value = fileList;
    ElMessage.warning('最多只能上传 5 张图片');
};

// const beforeUpload = (file) => {
//     const isLt5M = file.size / 1024 / 1024 < 5;

//     if (!isLt5M) {
//         ElMessage.error('上传图片大小不能超过 5MB!');
//         return false;
//     }

//     // 清空已存在的图片
//     fileList.value = [];
//     form.value.systemDiagram = '';

//     return true;
// };

const handleChange = (file, fileList) => {
    // fileList.length 表示当前选择的图片数量
    const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png' || file.raw.type === 'application/pdf';
    const isLt20M = file.size / 1024 / 1024 < 20;
    console.log('fileList', fileList);
    if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG / PNG / PDF 格式!');
        sysUpload.value.handleRemove(file)
        // 如果文件类型不符合要求，删除文件并返回
        return;
    }
    if (!isLt20M) {
        ElMessage.error('上传图片大小不能超过 20MB!');
        sysUpload.value.handleRemove(file)
        // 如果文件大小不符合要求，删除文件并返回
        return;
    }
    imgList.value = fileList;

    // 清空已存在的图片
    // if (fileList.length > 1) {
    //     fileList.splice(0, fileList.length - 1);
    // }

    // const reader = new FileReader();

    // reader.readAsDataURL(file.raw);
    // reader.onload = () => {
    //     fileList.push({ ...file, url: reader.result });
    //     // fileList.value = [{ ...file, url: reader.result }];
    // };

    // dialogImageUrl.value = file.url;

};

// let uploadCount = 0;

// const customRequest = async (parma) => {
//     try {
//         console.log('parma', parma);
//         const ImageData = new FormData();
//         ImageData.append('file', parma.file);
//         await proxy.$axios.post('/app/base/comm/upload', ImageData, {
//             headers: {
//                 'Content-Type': 'multipart/form-data'
//             }
//         }).then(res => {
//             formData.value.systemDiagram.push(res.data.data)
//             uploadCount += 1;

//             // Check if all files have been uploaded
//             if (uploadCount === imgList.value.length) {
//                 addDemand();
//             }

//         }).catch(err => {
//             ElMessage.error('图片上传失败');
//             parma.onError(err)
//             throw new Error(err);
//         })
//     } catch (error) {
//         ElMessage.error('图片上传失败');
//         console.error(error);
//     }
// }

const handlePreview = (file) => {
    dialogFileUrl.value = file.url;
    dialogVisibleimg.value = true;
    if (file.name.endsWith('.pdf')) {
        dialogFileType.value = 'pdf';
    } else {
        dialogFileType.value = 'img';
    }
};

const handleRemove = (file) => {
    imgList.value = imgList.value.filter(item => item.uid !== file.uid);
    // formData.value.systemDiagram = formData.value.systemDiagram.filter(item => item !== file.url);
    console.log('imgList', imgList);
};

const handleUploadSuccess = () => {
    // 上传成功后处理表单提交
};


const handleUploadError = (err) => {
    ElMessage.error('图片上传失败');
    throw new Error(err);

};


const uploadSysDiagram = async () => {

    for (const [index, file] of imgList.value.entries()) {
        const ImageData = new FormData();
        ImageData.append('file', file.raw);
        try {
            const res = await proxy.$axios.post('/app/base/comm/upload', ImageData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            if (res.data.code !== 1000) {
                ElMessage.error('图片上传失败');
                throw new Error(res.data.message);
            }
            formData.value.systemDiagram[index] = res.data.data
        } catch (err) {
            ElMessage.error('图片上传失败');
            throw new Error(err);
        }
    }
};

const uploadMeasurementFile = async () => {
    for (const item of formData.value.measurementInstruments) {
        for (let i = 0; i < item.fileList.manual.length; i++) {
            const file = item.fileList.manual[i];
            const ImageData = new FormData();
            ImageData.append('file', file.raw);
            try {
                const res = await proxy.$axios.post('/app/base/comm/upload', ImageData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                if (res.data.code !== 1000) {
                    ElMessage.error('文件上传失败');
                    throw new Error(res.data.message);
                }
                // 使用返回的URL替换文件对象中的URL
                item.fileList.manual[i] = res.data.data

            } catch (err) {
                ElMessage.error('文件上传失败');
                throw new Error(err);
            }
        }

        for (let i = 0; i < item.fileList.photos.length; i++) {
            const file = item.fileList.photos[i];
            const ImageData = new FormData();
            ImageData.append('file', file.raw);
            try {
                const res = await proxy.$axios.post('/app/base/comm/upload', ImageData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                if (res.data.code !== 1000) {
                    ElMessage.error('文件上传失败');
                    throw new Error(res.data.message);
                }

                // 使用返回的URL替换文件对象中的URL
                item.fileList.photos[i] = res.data.data

            } catch (err) {
                ElMessage.error('文件上传失败');
                throw new Error(err);
            }
        }

    }
};

const uploadControlInstruments = async () => {
    for (const item of formData.value.controlInstruments) {
        for (let i = 0; i < item.fileList.manual.length; i++) {
            const file = item.fileList.manual[i];
            const ImageData = new FormData();
            ImageData.append('file', file.raw);
            try {
                const res = await proxy.$axios.post('/app/base/comm/upload', ImageData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                if (res.data.code !== 1000) {
                    ElMessage.error('文件上传失败');
                    throw new Error(res.data.message);
                }
                // 使用返回的URL替换文件对象中的URL
                item.fileList.manual[i] = res.data.data

            } catch (err) {
                ElMessage.error('文件上传失败');
                throw new Error(err);
            }
        }

        for (let i = 0; i < item.fileList.photos.length; i++) {
            const file = item.fileList.photos[i];
            const ImageData = new FormData();
            ImageData.append('file', file.raw);
            try {
                const res = await proxy.$axios.post('/app/base/comm/upload', ImageData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                if (res.data.code !== 1000) {
                    ElMessage.error('文件上传失败');
                    throw new Error(res.data.message);
                }

                // 使用返回的URL替换文件对象中的URL
                item.fileList.photos[i] = res.data.data

            } catch (err) {
                ElMessage.error('文件上传失败');
                throw new Error(err);
            }
        }

    }
};




const addDemand = async () => {
    try {
        formData.value.userId = userInfo.value.unionid;


        await Promise.all([
            uploadSysDiagram(),
            uploadMeasurementFile(),
            uploadControlInstruments()
        ]);

        if (route.query.uuid) {
            formData.value.activeMessage.unshift({
                content: '修改需求',
                timestamp: new Date().toLocaleString()
            })
            const res = await proxy.$axios.post('/app/demand/info/updateDemand', formData.value)
            if (res.data.code !== 1000) {
                ElMessage.error('提交失败');
                throw new Error(res.data.msg);
            }
            router.push('/demandinfo');
            ElMessage.success('修改成功');
            return
        } else {
            formData.value.activeMessage.unshift({
                content: '初次提交需求',
                timestamp: new Date().toLocaleString()
            })
            const res = await proxy.$axios.post('/app/demand/info/addDemand', formData.value)
            console.log('res', res);
            if (res.data.code !== 1000) {
                ElMessage.error('提交失败');
                throw new Error(res.data.msg);
            }
            router.push('/demandinfo');
            ElMessage.success('提交成功');

        }


    } catch (err) {
        ElMessage.error("提交失败");
        throw new Error(err);
    }
};

const handleSubmit = async () => {
    ElMessageBox.confirm(
        `${route.query.uuid ? '是否确定修改需求？' : '是否确定提交需求？'}`,
        '确认提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        if (await checkLogin()) {
            formRef.value.validate(async (valid) => {
                if (valid) {
                    addDemand();
                } else {
                    ElMessage.error('请检查表单填写');
                    return false;
                }
            });
        }
    }).catch(() => {

    });


}
</script>

<style scoped>
:deep(#formContainer .el-form-item__label) {
    font-weight: bold;
    color: #606266;
    font-size: medium;
}

#info_btn:hover {
    color: #79bbff;
}

#vue-pdf-view {
    text-align: center;
    /* 内容溢出显示滚动条 */
    overflow: scroll;
    /* 隐藏x、y轴滚动条 */
    /* overflow-y: hidden; */
    overflow-x: hidden;
}

/* 设置滚动栏的宽、高 */
#vue-pdf-view::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

/* 设置滚动条的样式 */
#vue-pdf-view::-webkit-scrollbar-thumb {
    border-radius: 15px;
    background-color: #eee;
}

/* 鼠标经过滚动条变换颜色 */
#vue-pdf-view::-webkit-scrollbar-thumb:hover {
    background-color: #CBCBFF;
}
</style>